<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function ubah($s){
	$str = $s;
	$str = str_replace(" ","",$str);
	$str = str_replace("(","",$str);
	$str = str_replace(")","",$str);
	return $str;
}

function carijarak($awal,$tujuan){
	$origins = $awal;
	$destinations = implode("|", $tujuan);
	//var_dump($tujuan);
	$q = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origins."&destinations=".$destinations."&sensor=false";
	if(function_exists('curl_exec')){
		$ch = curl_init($q);
		@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true;
		$json = curl_exec($ch);
	}else{
		ini_set ('allow_url_fopen', 1);
		$json = file_get_contents($q) or die('url not loaded');
	}
	$details = json_decode($json, TRUE);
	/*var_dump($details);
	var_dump($q);
	exit();*/
	$hasil = array();
	for($i = 0; $i < count($tujuan); $i++){
		if(!isset($details['rows'][0]['elements'][$i]['distance'])){
			$hasil[$i] = -1;
		}else{
			$hasil[$i] = $details['rows'][0]['elements'][$i]['distance']['value'];
		}
	}

	return $hasil;
}

function subval_sort($a,$subkey) {
	foreach($a as $k=>$v) {
		$b[$k] = strtolower($v[$subkey]);
	}
	asort($b);
	foreach($b as $key=>$val) {
		$c[] = $a[$key];
	}
	return $c;
}

function urutan($awal,$akhir,$nama,$detail=FALSE){
	$awal = ubah($awal);
	foreach($akhir as &$isi){
		$isi = ubah($isi);
	}
	$jarak = carijarak($awal,$akhir);
	$hasil = array();
	$j=0;
	for($i = 0; $i < count($nama); $i++){
		if($jarak[$i]==-1)continue;
		$hasil[$j]['jarak']=$jarak[$i];
		$hasil[$j]['nama']=$nama[$i];
		$j++;
	}
	if(count($hasil)==0)return array();
	$hasil = subval_sort($hasil,'jarak');
		if($detail==FALSE){
	$hasil2 = array();
	foreach($hasil as $isi){
		$hasil2[] = $isi['nama'];
	}
	return $hasil2;
	}else{
		return $hasil;
	}
}
